package com.gavin.security;

import java.security.MessageDigest;

public class MD5 {
	public static String encode(String source) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] array = md.digest(source.getBytes("utf-8"));

			return Base64.encode(array);
		} catch (Exception e) {
			return null;
		}

	}

	public static String md5_hex(String source) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] array = md.digest(source.getBytes("utf-8"));

			return bytesToHexString(array);
		} catch (Exception e) {
			return null;
		}

	}

	public static String bytesToHexString(byte[] bysBytes) {
		String strDigital = "0123456789ABCDEF";

		StringBuilder sb = new StringBuilder("");
		byte[] bs = bysBytes;
		int bit;

		for (int i = 0; i < bs.length; i++) {
			bit = (bs[i] & 0x0f0) >> 4;
			sb.append(strDigital.substring(bit, bit + 1));
			bit = bs[i] & 0x0f;
			sb.append(strDigital.substring(bit, bit + 1));
		}

		return sb.toString();
	}
	
	public static void main(String[] args) {
		String strOutput = MD5.encode("This is a test");

		System.out.println(strOutput);
	}
}
